package com.ywjh.inter.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ywjh.inter.entity.InstitutionEntity;
import com.ywjh.inter.service.InstService;
import com.ywjh.inter.utils.StrUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class Inst extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -7876408955745672444L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=utf-8");

		JSONObject postData = StrUtil.getPostJSON(req);
		String act = postData.getString("act");
		JSONObject data = postData.getJSONObject("data");
		int r = 0;
		String e = "";
		JSONObject json = new JSONObject();
		switch (act) {
		case "list_sub_inst":
			int inst_id = data.getInt("inst_id");
			InstitutionEntity root = InstService.getInstance().findById(inst_id);
			if (root == null) {
				e = "机构不存在";
			} else {
				List<InstitutionEntity> list = InstService.getInstance().listByPid(inst_id);
				JSONArray array = new JSONArray();
				for (InstitutionEntity entity : list) {
					JSONObject instJson = new JSONObject();
					instJson.put("inst_id", entity.getId());
					instJson.put("name", entity.getName());
					instJson.put("pid", entity.getPid());
					instJson.put("type_id", entity.getInstitutionTypeId());
					array.add(instJson);
				}
				r = 1;
				json.put("d", array);
			}
			break;
		case "find":
			inst_id = data.getInt("inst_id");
			InstitutionEntity inst = InstService.getInstance().findById(inst_id);
			if (inst == null) {
				e = "机构不存在";
			}else {
				r = 1;
				JSONObject instJson = new JSONObject();
				instJson.put("inst_id", inst.getId());
				instJson.put("name", inst.getName());
				instJson.put("pid", inst.getPid());
				instJson.put("type_id", inst.getInstitutionTypeId());
				json.put("d", instJson);
			}
		}
		json.put("r", r);
		json.put("e", e);
		PrintWriter pw = resp.getWriter();
		pw.write(json.toString());
		pw.flush();
		pw.close();
	}
}
